package com.xjm.ips.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 判断当前用户是否具备某角色
 */
@Component
public class RoleManager implements AccessDecisionManager {
    @Override
    /**
     * Authentication对象中存储的是用户登录后的信息
     * collection是Filter过滤后返回的角色
     */
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //遍历过滤后的角色中是否在authentication中
        for (ConfigAttribute configAttribute : collection) {
            String needRole = configAttribute.getAttribute();//所需要的角色
            //如果是登陆即可访问的路径则查看是否登陆即可
            if ("ROLE_LOGIN".equals(needRole)) {
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new AccessDeniedException("您还没有登陆，请先登陆!!");
                } else {
                    return;
                }
            }
            //获取当前登陆用户的角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            //判断当前登陆用户是否包含所要求的角色中的任意一项
            for (GrantedAuthority authority : authorities) {
                //如果当前登陆用户的角色中有所需的角色
                if (authority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，无法访问!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
